package orxatas.travelme.activity;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;

import orxatas.travelme.R;
import orxatas.travelme.activity.DiaryActivity.ViewHolder;
import orxatas.travelme.databases.exceptions.UserNotInLocal;
import orxatas.travelme.entity.Comment;
import orxatas.travelme.entity.Entry;
import orxatas.travelme.entity.Group;
import orxatas.travelme.manager.DataManager;
import orxatas.travelme.manager.GroupManager;
import orxatas.travelme.manager.UserManager;
import orxatas.travelme.sync.AsyncNoticeCode;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.text.InputType;

public class GroupCommentActivity extends ListActivity implements AsyncActivity {
	private int id_grupo;
	private int owner_grupo;
	private String name_grupo;
	private static final String TAG = "Group Comment Activity";
	private Group myGroup;
	public ProgressDialog dialog;
	public CommentAdapter adapter;
	private RefreshListener listener;
	private boolean listenerRegistered;
	private EditText commentBox;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_comment);
		listener = new RefreshListener();
		
		// Obtener id de grupo y owner desde los extras del intent
	    id_grupo = getIntent().getIntExtra("id_grupo", -1);
	    owner_grupo = getIntent().getIntExtra("owner_grupo", -1);
	    name_grupo = getIntent().getStringExtra("name_grupo");
	    
	    if(id_grupo == -1 || owner_grupo == -1) {
	    	Log.e(TAG, "Fallo al iniciar la actividad. No se especifico id de grupo o nombre del duenyo de grupo.");
	    	finish();
	    }
	    
	    // Iniciamos el grupo
	    myGroup = new GroupManager(this).getGroup(id_grupo);
	    
	    prepareListData();
	}
	
	
	@Override
    protected void onResume() {
        super.onResume();

        if (!listenerRegistered) {
            registerReceiver(listener, new IntentFilter("SYNC_ACTION"));
            listenerRegistered = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (listenerRegistered) {
            unregisterReceiver(listener);
            listenerRegistered = false;
        }
    }
    
	private void prepareListData() {
		ArrayList<Comment> comments = myGroup.getComments();
		adapter = new CommentAdapter(this, R.layout.group_comment_row, comments);
		
		setListAdapter(adapter);
	}
	
	private class CommentAdapter extends ArrayAdapter<Comment> {
		private ArrayList<Comment> items;
		private Context ctx;
		private int resourceId;
		
		public CommentAdapter(Context context, int textViewResourceId,
				ArrayList<Comment> objects) {
			super(context, textViewResourceId, objects);
			this.ctx = context;
			this.items = objects;
			this.resourceId = textViewResourceId;
		}
		
		 public View getView(int position, View convertView, ViewGroup parent) {
		        View view = convertView;
		        if (view == null) {
		            LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		            view = inflater.inflate(resourceId, null);
		        }

		        Comment item = items.get(position);
		        if (item!= null) {
		            // My layout has only one TextView
		            TextView itemView = (TextView) view.findViewById(R.id.commentText);
		            TextView ownerView = (TextView) view.findViewById(R.id.commentOwner);
		            TextView dateView = (TextView) view.findViewById(R.id.groupcomment_date);
		            if (itemView != null && ownerView != null && dateView != null) {
		                // do whatever you want with your string and long
		                itemView.setText(item.getComment());
		                long date = ((long) item.getLastUpdate())*1000;
		                DateFormat formatter = DateFormat.getDateInstance();
		        		Date tmpDate = new Date();
		        		tmpDate.setTime(date);
		        		dateView.setText(formatter.format(date));
		                try {
							ownerView.setText(new UserManager(GroupCommentActivity.this).getUser(item.getIdAutor()).getUserName());
						} catch (UserNotInLocal e) {
							ownerView.setText("Id: "+item.getIdAutor());
						}
		            }
		         }

		        return view;
		    }
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.menu_group_comments, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.add_comment:
	    	// Agregar codigo para llamar a actividad o modal para nuevo comentario.
	    	getNewCommentDialog().show();
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	private AlertDialog getNewCommentDialog() {
		AlertDialog.Builder builder;
		AlertDialog alertDialog;

		commentBox = new EditText(this);
		commentBox.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
		commentBox.setHeight(300);
		
		builder = new AlertDialog.Builder(this);
		builder.setView(commentBox).setCancelable(true).setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// Aqui se crea el comentario
				String content = commentBox.getText().toString();
				GroupManager groupManager = new GroupManager(GroupCommentActivity.this);
				Comment newComment = groupManager.addCommentTo(myGroup.getIdOffline(), content);
				refreshCommentList();
			}
		}).setTitle("Agregar Comentario Nuevo").setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		alertDialog = builder.create();
		
		return alertDialog;
	}
	
	// Nested 'listener'
    protected class RefreshListener extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            // No need to check for the action unless the listener will
            // will handle more than one - let's do it anyway
            if (intent.getAction().equals("SYNC_ACTION")) {
            	new DataManager(GroupCommentActivity.this).syncAll();
            }
        }
    }
    
    private void refreshCommentList() {
    	adapter.clear();
    	myGroup = new GroupManager(this).getGroup(id_grupo);
        ArrayList<Comment> comments = myGroup.getComments();
        
        for(Comment it : comments) {
        	adapter.add(it);
        }
        
        adapter.notifyDataSetChanged();
    }

    /**
     * No se que codigo recibe cuando se agrega un comentario, asique le paso todos y au.
     */
	public void asyncNotice(AsyncNoticeCode code) {
		switch(code) {
		case GROUPS_CHANGED:
		case USERS_CHANGED:
		case GROUP_MANAGEMENT_ASYNC:
		case FRIENDS_CHANGED:
		case PLACES_CHANGED:
			refreshCommentList();
		}
	}

	public Activity getActivity() {
		return this;
	}

	public void syncStarted() {
		// TODO Auto-generated method stub
		
	}

	public void syncEnded() {
		// TODO Auto-generated method stub
		
	}

	public void syncAndWaitCallStarted() {
		if(dialog == null) {
			dialog = ProgressDialog.show(this, "", "Cargando...", true);
			dialog.setCancelable(false);
		}
	}

	public void syncAndWaitCallEnded(Object o, int syncAction) {
		if(dialog != null) {
			dialog.cancel();
			dialog = null;
		}
	}

}
